import { defineStore } from 'pinia'
import { store } from '../index'
// @ts-ignore
import { DictDataVO } from '@/api/system/dict/types'
import { getDictData } from '@/api/system/dict/dict.data'
import cache from '@/utils/cache'
import { CacheKey } from '@/utils/globalConstants'



export interface DictValueType {
  value: any
  label: string
  clorType?: string
  cssClass?: string
}
export interface DictTypeType {
  dictType: string
  dictValue: DictValueType[]
}
export interface DictState {
  dictMap: Map<string, any>
  isSetDict: boolean
}

const dictMap = cache.readCache(CacheKey.DictCache)

export const useDictStore = defineStore('dict', {
  state: (): DictState => ({
    dictMap: new Map<string, any>(),
    isSetDict: false
  }),
  getters: {
    getDictMap(): Recordable {
      if (dictMap) {
        this.dictMap = dictMap
      }
      return this.dictMap
    },
    getIsSetDict(): boolean {
      return this.isSetDict
    }
  },
  actions: {
    async setDictMap() {
      if (dictMap) {
        this.dictMap = dictMap
        this.isSetDict = true
      } else {
        // const res =  await getDictData(1)
        // console.log(res)
        // 设置数据
        const dictDataMap = new Map<string, any>()
        // res.forEach((dictData: DictDataVO) => {
        //   // 获得 dictType 层级
        //   const enumValueObj = dictDataMap[dictData.dictType]
        //   if (!enumValueObj) {
        //     dictDataMap[dictData.dictType] = []
        //   }
        //   // 处理 dictValue 层级
        //   dictDataMap[dictData.dictType].push({
        //     value: dictData.value,
        //     label: dictData.label,
        //     colorType: dictData.colorType,
        //     cssClass: dictData.cssClass
        //   })
        // })
        this.dictMap = dictDataMap
        this.isSetDict = true
        cache.writeCache(dictDataMap,CacheKey.DictCache,60)
      }
    },
    getDictByType(type: string) {
      if (!this.isSetDict) {
        this.setDictMap()
      }
      return this.dictMap[type]
    },
    async resetDict() {
      cache.deleteCache(CacheKey.DictCache)
      // const res = await getSimpleDictDataList()
      // 设置数据
      const dictDataMap = new Map<string, any>()
      // res.forEach((dictData: DictDataVO) => {
      //   // 获得 dictType 层级
      //   const enumValueObj = dictDataMap[dictData.dictType]
      //   if (!enumValueObj) {
      //     dictDataMap[dictData.dictType] = []
      //   }
      //   // 处理 dictValue 层级
      //   dictDataMap[dictData.dictType].push({
      //     value: dictData.value,
      //     label: dictData.label,
      //     colorType: dictData.colorType,
      //     cssClass: dictData.cssClass
      //   })
      // })
      this.dictMap = dictDataMap
      this.isSetDict = true
      cache.writeCache(dictDataMap, CacheKey.DictCache,60)
    }
  }
})

export const useDictStoreWithOut = () => {
  return useDictStore(store)
}
